<template>
  <page-container>
    <app-card>
      <template #header>
        数据筛选
      </template>
      <el-form
        ref="form"
        :inline="true"
        :model="listParams"
        :disabled="listLoading"
        label-width="70px"
        @submit.prevent="handleQuery"
      >
        <el-form-item label="商品分类">
          <el-select
            v-model="listParams.pid"
            placeholder="请选择"
            clearable
            @change="loadList"
          >
            <el-option
              v-for="item in productCates"
              :key="item.id"
              :label="`${item.html}${item.cate_name}`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="状态">
          <el-select
            v-model="listParams.is_show"
            placeholder="请选择，默认是显示状态"
            clearable
            @change="loadList"
          >
            <el-option
              v-for="item in productStatus"
              :key="item.status"
              :label="item.label"
              :value="item.status"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="分类名称">
          <el-input
            v-model="listParams.cate_name"
            placeholder="请输入分类名称关键字"
            clearable
            @change="loadList"
            style="width: 300px;"
          >
            <template #append>
              <el-button
                icon="el-icon-search"
                @click="loadList"
              />
            </template>
          </el-input>
        </el-form-item>
      </el-form>
    </app-card>
    <app-card>
      <template #header>
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="handleAddCategory"
        >
          添加分类
        </el-button>
      </template>
      <el-table
        :data="list"
        v-loading="listLoading"
        style="width: 100%"
        row-key="cate_name"
      >
        <el-table-column
          prop="id"
          label="ID"
          min-width="120"
        />
        <el-table-column
          prop="cate_name"
          label="分类名称"
        />
        <el-table-column
          prop="id"
          label="分类图标"
        >
          <template #default="scope">
            <el-image
              style="width: 40px; height:40px"
              :src="scope.row.pic"
              :preview-src-list="[scope.row.pic]"
            >
              <template #error>
                <div class="image-slot">
                  <i
                    class="el-icon-picture"
                    style="font-size: 20px; margin: 10px auto; color: rgb(219, 219, 219);"
                  />
                </div>
              </template>
            </el-image>
          </template>
        </el-table-column>

        <el-table-column
          prop="sort"
          label="排序"
        />
        <el-table-column
          label="状态"
          width="150"
        >
          <template #default="scope">
            <el-switch
              v-model="scope.row.is_show"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"
              :loading="scope.row.statusLoading"
              active-text="显示"
              inactive-text="隐藏"
              @change="handleUpdateStatus(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column
          min-width="120px"
          label="操作"
          fixed="right"
          align="center"
        >
          <template #default="{ row }">
            <el-button
              @click="handleEdit(row.id)"
              type="text"
            >
              编辑
            </el-button>
            <el-popconfirm
              title="确定要删除分类吗？（删除后不可恢复哦）"
              @confirm="handleDelete(row.id)"
            >
              <template #reference>
                <el-button type="text">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <app-pagination
        v-model:page="listParams.page"
        v-model:limit="listParams.limit"
        :list-count="listCount"
        :load-list="loadList"
        :disabled="listLoading"
      />
    </app-card>
  </page-container>
  <category-form
    v-model="formVisible"
    v-model:cate-id="cateId"
    @success="handleFormSuccess"
  />
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { getProductCategorys, getCategoryTree, updateCategoryStatus, removeCategory } from '@/api/product'
import { ElMessage } from 'element-plus'
import type { CategoryListParams, ProductCategory } from '@/api/types/product'
import CategoryForm from './CategoryForm.vue'

const productCates = ref<ProductCategory[]>([])
const productStatus = ref<{
  label: string
  status: number
}[]>([
  {
    label: '显示',
    status: 1
  },
  {
    label: '隐藏',
    status: 0
  }
])
const list = ref<ProductCategory[]>([])
const listCount = ref(0)
const listLoading = ref(false)
const listParams = reactive<CategoryListParams>({
  pid: undefined,
  is_show: undefined,
  page: 1,
  cate_name: undefined,
  limit: 10
})

const formVisible = ref(false)
const cateId = ref<number | null>(null)

onMounted(() => {
  loadList()
  loadProductCates()
})

const handleAddCategory = () => {
  formVisible.value = true
}

const loadList = async () => {
  listLoading.value = true
  const data = await getProductCategorys(listParams).finally(() => {
    listLoading.value = false
  })
  data.list.forEach(item => {
    item.statusLoading = false
  })
  list.value = data.list
  listCount.value = data.count

  // 更新商品分类
  loadProductCates()
}

const loadProductCates = async () => {
  const data = await getCategoryTree(1)
  productCates.value = data
}

const handleQuery = () => {
  listParams.page = 1
  loadList()
}

const handleUpdateStatus = async (item: ProductCategory) => {
  item.statusLoading = true
  await updateCategoryStatus(item.id, item.is_show).finally(() => {
    item.statusLoading = false
  })
  ElMessage.success(`设置${item.is_show ? '显示' : '隐藏'}成功`)
  loadList()
}

const handleDelete = async (id: number) => {
  await removeCategory(id)
  ElMessage.success('删除成功')
  loadList()
}

const handleEdit = (id: number) => {
  cateId.value = id
  formVisible.value = true
}

const handleFormSuccess = () => {
  formVisible.value = false
  loadList()
}

</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.demo-table-expand {
  font-size: 0;
  :deep(label) {
    width: 90px;
    color: #99a9bf;
  }
  :deep(.el-form-item) {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
}

  </style>
